package com.yingxin.yxerp.module.activiti.biz.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.yingxin.yx.framework.commons.activiti.ApprovalStatus;
import com.yingxin.yx.framework.commons.activiti.def.TaskDef;
import com.yingxin.yx.framework.commons.helper.ListHelper;
import com.yingxin.yxerp.module.activiti.constants.CarbonCopyConst;
import com.yingxin.yxerp.module.activiti.entity.ActivitiBizInfo;
import com.yingxin.yxerp.module.common.BusinessTypeHelper;
import com.yingxin.yxerp.module.message.constant.UserMsgType;
import com.yingxin.yxerp.module.message.entity.UserMessage;
import com.yingxin.yxerp.module.message.service.IUserMessageService;
import com.yingxin.yxerp.module.organization.entity.Department;
import com.yingxin.yxerp.module.organization.entity.DepartmentMgr;
import com.yingxin.yxerp.module.organization.entity.User;
import com.yingxin.yxerp.module.organization.service.IDepartmentMgrService;
import com.yingxin.yxerp.module.organization.service.IDepartmentService;
import com.yingxin.yxerp.module.organization.service.IUserService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CarbonCopyService {

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IDepartmentMgrService departmentMgrService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserMessageService userMessageService;

    /**
     * 抄送
     *
     * @param processInstance
     * @param task
     */
    public void creatCarbonCopy(ProcessInstance processInstance, Task task, ActivitiBizInfo bizInfo,
                                ApprovalStatus approvalStatus) {
        // 查询相关task定义，里面包含了抄送信息
        List<TaskDef> taskDefList = JSON.parseArray(bizInfo.getBpmnTask(), TaskDef.class);
        Map<String, TaskDef> taskDefMap = ListHelper.toMap(TaskDef::getElementId, taskDefList);
        TaskDef taskDef = taskDefMap.get(task.getTaskDefinitionKey());
        // 抄送类型
        List<String> ccTypeList = taskDef.getCcType();
        if (CollectionUtil.isEmpty(ccTypeList)) {
            return;
        }
        for (String ccType : ccTypeList) {
            if (CarbonCopyConst.USER.equals(ccType)) {
                // 指定用户
                List<String> userIds = taskDef.getCc();
                if (CollectionUtil.isNotEmpty(userIds)) {
                    for (String userId : userIds) {
                        UserMessage message = buildMessage(processInstance, task, bizInfo, approvalStatus);
                        userMessageService.create(message, processInstance.getStartUserId(), userId);
                    }
                }
            } else if (CarbonCopyConst.DEPT_MGR.equals(ccType)) {
                // 部门领导
                String deptId = taskDef.getCcDepartment();
                if (StringUtils.isNotBlank(deptId)) {
                    Department dept = departmentService.getById(deptId);
                    List<DepartmentMgr> deptMgrList = departmentMgrService.listByDeptId(dept.getId());
                    if (CollectionUtil.isNotEmpty(deptMgrList)) {
                        for (DepartmentMgr mgr : deptMgrList) {
                            UserMessage message = buildMessage(processInstance, task, bizInfo, approvalStatus);
                            userMessageService.create(message, processInstance.getStartUserId(), mgr.getManagerId());
                        }
                    }
                }
            } else if (CarbonCopyConst.GROUPS.equals(ccType)) {
                // 组/部门
                List<String> deptIds = taskDef.getCcGroup();
                if (CollectionUtil.isNotEmpty(deptIds)) {
                    for (String deptId : deptIds) {
                        List<User> users = userService.listByDeptId(deptId);
                        for (User user : users) {
                            UserMessage message = buildMessage(processInstance, task, bizInfo, approvalStatus);
                            userMessageService.create(message, processInstance.getStartUserId(), user.getId());
                        }
                    }
                }
            } else if (CarbonCopyConst.APPLICANT_MGR.equals(ccType)) {
                // 申请人主管
                User user = userService.getById(processInstance.getStartUserId());
                Department dept = departmentService.getById(user.getDeptId());
                if (dept != null) {
                    List<DepartmentMgr> deptMgrList = departmentMgrService.listByDeptId(dept.getId());
                    if (CollectionUtil.isNotEmpty(deptMgrList)) {
                        for (DepartmentMgr mgr : deptMgrList) {
                            UserMessage message = buildMessage(processInstance, task, bizInfo, approvalStatus);
                            userMessageService.create(message, processInstance.getStartUserId(), mgr.getManagerId());
                        }
                    }
                }
            }
        }
    }


    private UserMessage buildMessage(ProcessInstance processInstance, Task task, ActivitiBizInfo bizInfo,
                                     ApprovalStatus approvalStatus) {
        UserMessage message = new UserMessage(bizInfo.getBizId(), bizInfo.getBizNo(), bizInfo.getBizType());
        message.setMessageType(UserMsgType.SP_CC.getType());
        message.setMessageContent(String.format("[%s-%s]抄送给你", BusinessTypeHelper.getName(bizInfo.getBizType()), bizInfo.getBizNo()));
        message.setProcessInstanceId(processInstance.getId());
        message.setTaskId(task.getId());
        return message;
    }


}
